import { defineStore } from 'pinia'

import { login, logout } from '@/api/system/account'
import { getInfo } from '@/api/system/user'

import { constantRoutes } from '@/router'

import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'

import { hasChildren, isLinkMenu, isFolderMenu, isMenu } from '@/utils/app'
import { removeToken } from '@/utils/auth'

import { useTagsViewStore } from '@/store/tagsView'

export const useAccountStore = defineStore('accountStore', {
  state: () => {
    return {
      name: 'xx管理员',
      permissions: [],
      menus: [],
      showLoginForm: false
    }
  },
  getters: {
    routes: (state) => {
      const asyncRoutes = toRoutes(state.menus, true)
      asyncRoutes.push({
        path: '/:pathMatch(.*)*',
        redirect: '/404',
        hidden: true
      })
      return asyncRoutes
    },
    sidebars: (state) => {
      return toSideBars(state.menus).concat(
        constantRoutes.filter((item) => !item.hidden)
      )
    }
  },
  actions: {
    async Login(data) {
      await login(data)
      // await getInfo()
    },

    async GetInfo() {
      const { data } = await getInfo()
      this.name = data.nickName
      this.permissions = data.permissions || []
      this.menus = data.menus || []
    },

    async Logout() {
      await logout()
      removeToken()
      this.name = ''
      // this.avatar = ''
      this.permissions = []
      this.menus = []

      const tagsViewStore = useTagsViewStore()
      tagsViewStore.deleteAllViews()
    },

    setShowLoginForm(val) {
      this.showLoginForm = val
    }
  }
})

function toSideBars(menus, parentPath = '') {
  const result = []
  for (const menu of menus) {
    const sidebar = {
      id: menu.id,
      parentId: menu.parentId,
      type: menu.type,
      title: menu.title,
      // 父路径与子路径拼接
      path: toSidebarPath(menu, parentPath),
      icon: menu.icon
    }
    result.push(sidebar)

    if (hasChildren(menu)) {
      sidebar.children = toSideBars(menu.children, sidebar.path)
    }
  }
  return result
}

function toSidebarPath(menu, parentPath) {
  if (isLinkMenu(menu)) {
    // 超链接直接返回
    return menu.path
  }
  if (menu.path) {
    return menu.path.charAt(0) === '/'
      ? parentPath + menu.path
      : parentPath + '/' + menu.path
  }
  return ''
}

function toRoutes(menus, rootLevel = false) {
  const result = []
  for (const menu of menus) {
    // 超链接不在vue router中导航
    if (isLinkMenu(menu)) {
      continue
    }
    result.push(toRoute(menu, rootLevel))
  }
  return result
}

/**
 * component组件路径：
 * rootLevel && isFolderMenu() => { component : Layout}
 * rootLevel && isMenu() => { component : Layout, children: { component : loadView() }}
 * !rootLevel && isFolderMenu() => { component : ParentView}
 * !rootLevel && isMenu() => { component : loadView()}
 *
 * name命名路由：
 * isMenu() => { name : menu.title}
 *
 * path路由路径：
 * rootLevel && isFolderMenu() => { path : '/' + menu.path}
 * rootLevel && isMenu() => { path : '/' + menu.path, children: { path : '' }}
 * !rootLevel && isFolderMenu() => { path : menu.path}
 * !rootLevel && isMenu() => { path : menu.path}
 */
function toRoute(menu, rootLevel) {
  const folderMenu = isFolderMenu(menu)
  const clickMenu = isMenu(menu)

  const path = toRoutePath(menu)

  if (rootLevel) {
    if (folderMenu) {
      return {
        component: Layout,
        path: '/' + path,
        redirect: 'noRedirect',
        meta: { title: menu.title },
        children: hasChildren(menu) ? toRoutes(menu.children) : undefined
      }
    }

    if (clickMenu) {
      return {
        component: Layout,
        path: '/',
        children: [
          {
            name: menu.name,
            path: path,
            meta: { title: menu.title, cache: menu.cacheFlag === 1 },
            component: loadView(menu.component)
          }
        ]
      }
    }
    return undefined
  }

  if (folderMenu) {
    return {
      component: ParentView,
      path: path,
      redirect: 'noRedirect',
      meta: { title: menu.title },
      children: hasChildren(menu) ? toRoutes(menu.children) : undefined
    }
  }

  if (clickMenu) {
    return {
      component: loadView(menu.component),
      path: path,
      meta: { title: menu.title, cache: menu.cacheFlag === 1 },
      name: menu.name
    }
  }
  // 不支持的menu类型
  return undefined
}

function toRoutePath(menu) {
  return menu.path && menu.path.charAt(0) === '/'
    ? menu.path.substr(1)
    : menu.path
}

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('../views/**/*.vue')

function loadView(view) {
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0]
    if (dir === view) {
      return () => modules[path]()
    }
  }
  return null
}
